package com.solution.wx.my.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.solution.admin.auth.service.UserService;
import com.solution.admin.customer.service.CustomerLevelService;
import com.solution.admin.order.constants.OrderConstants;
import com.solution.admin.order.entity.OrderDetailEntity;
import com.solution.admin.order.entity.OrderEntity;
import com.solution.admin.order.service.OrderDetailService;
import com.solution.admin.order.service.OrderService;
import com.solution.admin.product.entity.ProductEntity;
import com.solution.admin.product.entity.ProductSpecEntity;
import com.solution.admin.product.service.ProductService;
import com.solution.common.constants.PublicStatus;
import com.solution.common.controller.BaseController;
import com.solution.common.utils.string.StringUtil;
import com.solution.pc.order.entity.OrderEvaluationEntity;
import com.solution.pc.order.service.OrderEvaluationService;
import com.solution.wx.core.util.WechatUtil;

@RequestMapping("/wx/evaluation")
@Controller
public class WxEvaluationController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(WxEvaluationController.class);

	@Autowired
	private OrderEvaluationService orderEvaluationService;

	@Autowired
	private OrderService orderService;

	@Autowired
	private OrderDetailService orderDetailService;

	@Autowired
	private UserService userService;
	
	@Autowired
	private CustomerLevelService customerLevelService;
	
	@Autowired
	private ProductService productService;

	/**
	 * 跳转至订单评价页面
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2017年12月4日 下午2:58:59
	 */
	@RequestMapping("/toOrderEvaluation")
	public String toOrderEvaluation(HttpServletRequest request) {
		String orderCode = request.getParameter("orderCode");
		String productId = request.getParameter("productId");
		
		//订单评价
		if (StringUtil.isNotNull(orderCode)) {
			OrderEntity order = orderService.getOrderByCode(orderCode);
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("orderCode", orderCode);
			List<OrderDetailEntity> orderDetailList = orderDetailService.listOrderDetail(paramMap);
			for (OrderDetailEntity detailEntity : orderDetailList) {
				List<ProductSpecEntity> productSpecList = JSON.parseArray(detailEntity.getProductSpec(), ProductSpecEntity.class);
				detailEntity.setProductSpecList(productSpecList);
			}
			
			//只能进入自己的订单
			if (null == order || order.getCustomerId() != getCustomerId()) {
				return "redirect:/wx/index";
			}

			request.setAttribute("order", order);
			request.setAttribute("orderDetailList", orderDetailList);
		}
		
		//商品评价
		if (StringUtil.isNotNull(productId)) {
			ProductEntity product = productService.getProductById(Long.parseLong(productId));
			OrderDetailEntity detailEntity = new OrderDetailEntity();
			detailEntity.setId(product.getId());
			detailEntity.setProductCode(product.getProductCode());
			detailEntity.setProductName(product.getProductName());
			detailEntity.setImagePath(product.getProductImgPath());
			request.setAttribute("orderDetailList", Lists.newArrayList(detailEntity));
		}
		
		// 查询微信调用接口信息
		String jsapi_ticket = WechatUtil.getJspiTicket();
		String url = request.getRequestURL().toString();
		String urlParam = request.getQueryString();
		if (StringUtil.isNotNull(urlParam)) {
			url = url + "?" + urlParam;
		}
		Map<String, String> sign = WechatUtil.sign(jsapi_ticket, url);
		request.setAttribute("appId", WechatUtil.APPID);
		request.setAttribute("timestamp", sign.get("timestamp"));
		request.setAttribute("nonceStr", sign.get("nonceStr"));
		request.setAttribute("signature", sign.get("signature"));
		
		//返回链接
		request.setAttribute("backUrl", request.getParameter("backUrl"));
		
		return "wx/my/order_evaluation";
	}

	/**
	 * 提交评论
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2017年12月4日 下午2:59:07
	 */
	@RequestMapping("/commitEvaluation")
	@ResponseBody
	public Map<String, Object> commitEvaluation(HttpServletRequest request){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String orderCode = request.getParameter("orderCode");
		String evaluationJson = request.getParameter("evaluationList");
		JSONArray array = JSONArray.parseArray(evaluationJson);
		OrderEntity order = null;
		if (StringUtil.isNotNull(orderCode)) {
			order = orderService.getOrderByCode(orderCode);
		}
		//商品评价可以不用购买
//		//只能评价自己的订单,只能评价未评价订单
//		if (null == order || order.getCustomerId() != getCustomerId()) {
//			resultMap.put(PublicStatus.RESULT_CODE, "0");
//			resultMap.put(PublicStatus.RESULT_MSG, "只能评价自己的订单");
//			return resultMap;
//		}
//		if (null != order.getAppraiseFlag() && order.getAppraiseFlag().equals("1")) {
//			resultMap.put(PublicStatus.RESULT_CODE, "0");
//			resultMap.put(PublicStatus.RESULT_MSG, "该订单已评");
//			return resultMap;
//		}
		List<OrderEvaluationEntity> evaluationList = new ArrayList<OrderEvaluationEntity>();
		for (int i = 0; i < array.size(); i++) {
			JSONObject object = array.getJSONObject(i);
			OrderEvaluationEntity evaluation = new OrderEvaluationEntity();
			if (null != order) {
				evaluation.setOrderId(order.getId());
				evaluation.setOrderCode(orderCode);
			}
			evaluation.setProductCode(object.getString("productCode"));
			evaluation.setProductName(object.getString("productName"));
			evaluation.setImagePath(object.getString("imagePath"));
			evaluation.setScore(object.getInteger("score"));
			evaluation.setContent(object.getString("content"));
			evaluation.setFilePath(object.getString("filePath"));
			evaluation.setUserId(getCustomerId());
			evaluation.setUserName(getCustomer().getUserName());
			evaluation.setCreater(getCustomer().getUserName());
			evaluation.setHeadImage(getCustomer().getHeadImage());
			evaluation.setLevelName(getCustomerLevel());
			evaluation.setChannel(OrderConstants.ORDER_CHANNEL.WX.getCode());;
			evaluationList.add(evaluation);
		}
		Long orderId = null;
		if (null != order) {
			orderId = order.getId();
		}
		int result = orderEvaluationService.saveOrderEvaluation(evaluationList, orderId);
		resultMap.put(PublicStatus.RESULT_CODE, result>0?"1":"0");
		resultMap.put(PublicStatus.RESULT_MSG, result>0?"评价成功":"评价失败");
		return resultMap;
	}
}
